<?php 
/**
* Provide locking mechanism for shared file access.
*@author Willy Gardiol <willy@gardiol.org>
*@version 1.0
*@package Core
*@subpackage Unused
*@todo Make Atom package use this FileLock class! (its unused at the moment)
*@todo Document this class
*/
class FileLock 
{
	private $filename = "";
	private $lockfile = "";
	private $has_lock = false;

	public function __construct( $filename )
	{
		$this->filename = $filename;
		$this->lockfile =  "".$filename."_lock";
	}

	public function __destruct()
	{
		if ( $this->has_lock )
			$this->Unlock();
	}

	public function TestLock()
	{
		return file_exists( $this->lockfile );
	}
	public function WaitForLock( $timeout = 60)
	{
		if ( $timeout > 60 )
			$timeout = 60;
		while (  $this->TestLock() && !$this->has_lock && ($timeout > 0) )
		{
			$timeout--;
			sleep(1);
		}
		return $this->Lock();
	}

	public function Lock()
	{
		if ( !$this->TestLock() && !$this->has_lock )
			$this->has_lock = touch( $this->lockfile );
		return $this->has_lock;
	}

	public function Unlock()
	{
		if ( $this->TestLock() && $this->has_lock )
			$this->has_lock = unlink( $this->lockfile );
		return !$this->has_lock;
	}
}

?>